package com.example.demo.common.utils;

import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;
import com.drew.metadata.MetadataException;
import com.drew.metadata.exif.ExifIFD0Directory;
import com.drew.metadata.jpeg.JpegDirectory;
import javafx.scene.transform.Rotate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashSet;
import java.util.Set;

@Component
public class ImgUtils {

    /**
     * 读数据库，获取图片输入流
     * @return
     */
    public FileInputStream query_getPhotoImageBlob(String adress) {
        FileInputStream is = null;
        File filePic = new File(adress);
        try {
            is = new FileInputStream(filePic);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return is;

    }
    /*
     * 获取图片并显示在页面
     * @return
     * @throws SQLException
     */
    @RequestMapping(value = "queryPic")
    public void queryPic(@RequestParam(required=false) String address
            , HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (StringUtils.isNotBlank(address)){
            response.setContentType("image/jpeg");
            FileInputStream is =this.query_getPhotoImageBlob(address);

            if (is != null){
                int i = is.available(); // 得到文件大小
                byte data[] = new byte[i];
                is.read(data); // 读数据
                is.close();
                response.setContentType("image/jpeg");  // 设置返回的文件类型
                OutputStream toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
                toClient.write(data); // 输出数据
                toClient.close();
            }
        }
    }

    /**
     * 根据图片文件的EXIF Orientation信息选择图片
     * @param jpegFile
     * @return
     */
    public static String rotateImgByExif(File jpegFile){
        if(!jpegFile.exists()){
            return "文件不存在";
        }
        String message;
        String filePath = jpegFile.getPath();
        String fileExt = filePath.substring(filePath.lastIndexOf("."));
        //jpg|jpeg|bmp|png
        Set<String> imgSet = new HashSet<String>();
        imgSet.add(".jpeg");
        imgSet.add(".jpg");
        imgSet.add(".png");
        if(!imgSet.contains(fileExt)){
            return "图片格式不对(格式要求jpg|jpeg|png),当前文件后缀："+fileExt;
        }
        try {
            String needDescription = getImgInfoExif(jpegFile,"Orientation");
            System.out.println("ImgUtils-rotateImgByExif-needDescription:"+needDescription);
            int tag = getOrientation(needDescription);
            int angle = getAngleByTag(tag);
            BufferedImage src = ImageIO.read(jpegFile);
            BufferedImage des = RotateImage.Rotate(src, angle);
            ImageIO.write(des,fileExt.substring(1), new File(filePath));
            message = "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "文件调整失败";
        }
        return message;
    }

    /**
     * 查询Img里的Exif里的对应的信息描述   当前是查Orientation
     * @param jpegFile
     * @param needTagName
     * @return
     */
    public static String getImgInfoExif(File jpegFile,String needTagName){
        try{
            Metadata metadata = ImageMetadataReader.readMetadata(jpegFile);
            for (Directory directory : metadata.getDirectories()) {
                for (Tag tag : directory.getTags()) {
                    String tagName = tag.getTagName();
                    if(needTagName.equals(tagName)){
                        return tag.getDescription();
                    }
                }
            }
        }catch (Exception e){
            return "error";
        }
        return "";
    }

    /**
     * 获得当前方向选择的tag,根据tag判断其的角度
     * @param orientation
     * @return
     */
    public static int getOrientation(String orientation)
    {
        int tag = 0;
        if ("Top, left side (Horizontal / normal)".equalsIgnoreCase(orientation)) {
            tag = 1;
        } else if ("Top, right side (Mirror horizontal)".equalsIgnoreCase(orientation)) {
            tag = 2;
        } else if ("Bottom, right side (Rotate 180)".equalsIgnoreCase(orientation)) {
            tag = 3;
        } else if ("Bottom, left side (Mirror vertical)".equalsIgnoreCase(orientation)) {
            tag = 4;
        } else if ("Left side, top (Mirror horizontal and rotate 270 CW)".equalsIgnoreCase(orientation)) {
            tag = 5;
        } else if ("Right side, top (Rotate 90 CW)".equalsIgnoreCase(orientation)) {
            tag = 6;
        } else if ("Right side, bottom (Mirror horizontal and rotate 90 CW)".equalsIgnoreCase(orientation)) {
            tag = 7;
        } else if ("Left side, bottom (Rotate 270 CW)".equalsIgnoreCase(orientation)) {
            tag = 8;
        }
        return  tag;
    }

    /**
     * 根据tag获得需要旋转的angle
     * @param tag
     * @return
     */
    public static int getAngleByTag(int tag){
        int angel = 0;
        // 原图片的方向信息
        if(6 == tag ){
            //6旋转90
            angel = 90;
        }else if( 3 == tag){
            //3旋转180
            angel = 180;
        }else if( 8 == tag){
            //8旋转90
            angel = 270;
        }
        return angel;
    }


    public static void main(String[] args) throws ImageProcessingException, IOException {
        File jpegFile= new File("C:\\Users\\Administrator\\Desktop\\test (2).jpg");
        if(!jpegFile.exists()){
            System.out.println("文件不存在");
        }
        String filePath = jpegFile.getPath();
        String fileExt = filePath.substring(filePath.lastIndexOf(".")+1);
        System.out.println(filePath);
        System.out.println("fileExt:"+fileExt);
        try{
            Metadata metadata = ImageMetadataReader.readMetadata(jpegFile);
            int i = 1;
            for (Directory directory : metadata.getDirectories()) {
                System.out.println("=========="+(i++)+"===========");
                for (Tag tag : directory.getTags()) {
                    System.out.print(tag.getTagName()+"-------->");
                    System.out.println(tag.getDescription());
                }
            }
        }catch (Exception e){

        }
        //Metadata metadata = ImageMetadataReader.readMetadata(jpegFile);
        //Directory directory = metadata.getDirectory(ExifIFD0Directory.class);
        /*Iterable<Directory> directories = metadata.getDirectories();
        JpegDirectory jpegDirectory = (JpegDirectory)metadata.getDirectory(JpegDirectory.class);

        int orientation = 1;
        try {
            orientation = directory.getInt(ExifIFD0Directory.TAG_ORIENTATION);
        } catch (MetadataException me) {
            logger.warn("Could not get orientation");
        }

        System.out.println(orientation);
*/
        /*int angel = 0;
        // Exif信息中方向　　
        int orientation = directory.getInt(ExifDirectory.TAG_ORIENTATION);
        // 原图片的方向信息
        if(6 == orientation ){
            //6旋转90
            angel = 90;
        }else if( 3 == orientation){
            //3旋转180
            angel = 180;
        }else if( 8 == orientation){
            //8旋转90
            angel = 270;
        }*/

        //BufferedImage src = ImageIO.read(jpegFile);
        //BufferedImage des = RotateImage.Rotate(src, 90);
        //ImageIO.write(des,"jpg", new File("C:\\Users\\Administrator\\Desktop\\IMG_0362.JPG"));

    }
}
